<template>
  <div class="login">
    <div class="relative login-img flex-col items-center hidden md:flex">
      <div>
        <img class="mb-4" src="https://xc-erp-login.oss-cn-shenzhen.aliyuncs.com/login/logo_login.png" />
        <img src="https://xc-erp-login.oss-cn-shenzhen.aliyuncs.com/login/text.png" />
      </div>
      <img class="login-bg-img" src="https://xc-erp-login.oss-cn-shenzhen.aliyuncs.com/login/illustration.png" />
    </div>
    <el-form v-loading="loading" ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="login-form-box">
        <div class="login-form-toggle">
          <svg-icon v-if="loginQr" icon-class="company"></svg-icon>
          <svg-icon v-else icon-class="qr"></svg-icon>
        </div>
        <div class="login-form-popover">
          <small>{{ loginQr ? "账户登录" : "扫码登录" }}</small>
          <img src="@/assets/images/popover.png" />
        </div>
        <div class="hotZone" @click="handleToggleType"></div>
        <h3 class="title">信诚创新ERP</h3>
        <div class="flex flex-col items-center mb-2">
          <div class="text-center text-xs text-gray-400 mb-2">请选择公司</div>
          <el-select v-model="loginForm.tenant_id" size="large" class="login-company mb-2 w-3/4" placeholder="选择公司">
            <el-option v-for="(d, i) in companyList" :key="i" :label="d.tenant_name" :value="d.tenant_id"></el-option>
          </el-select>
          <div style="display: none">
            <el-input v-model="loginForm.account" type="text" size="large" auto-complete="on" />
            <el-input v-model="loginForm.account" type="text" size="large" autocomplete="on" />
          </div>
        </div>
        <template v-if="loginQr">
          <div id="login_container" class="login-qr">
            <!-- <svg-icon icon-class="qr"></svg-icon> -->
          </div>
          <div class="mb-2 text-sm text-center text-gray-600">请使用飞书扫描二维码登录</div>
        </template>
        <template v-else>
          <el-form :model="loginForm">
            <el-form-item prop="account">
              <el-input v-model="loginForm.account" type="text" size="large" auto-complete="on" placeholder="登录账户">
                <!-- <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template> -->
              </el-input>
            </el-form-item>
            <el-form-item prop="password" class="mt-9">
              <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleLogin">
                <!-- <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template> -->
              </el-input>
            </el-form-item>
            <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
            <el-form-item style="width: 100%" class="mt-11">
              <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
                <span v-if="!loading">立即登录</span>
                <span v-else>登 录 中...</span>
              </el-button>
              <div style="float: right" v-if="register">
                <router-link class="link-type" :to="'/register'">立即注册</router-link>
              </div>
            </el-form-item>
          </el-form>
        </template>
        <div class="login-form-phone">如需申请账户或找回密码，请联系Jack(15989439756)</div>
        <!-- <div class="text-center mt-1"><el-button type="text"><span class="text-sm">飞书授权登录</span></el-button></div> -->
      </div>
    </el-form>
    <div class="login-right"></div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © {{ year }} 深圳市信诚数字科技有限公司 版权所有 粤ICP备17046708号</span>
    </div>
  </div>
</template>
<script setup>
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from "@/store/modules/user"
import { nextTick, ref } from "vue"
import { ElMessage } from "element-plus"
import { getFeishuApp } from "@/api/login"
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const loginQr = ref(true)
let companyList = ref([{ tenant_id: "1", tenant_name: "深圳市信诚创新技术有限公司" }])
const loginForm = ref({
  tenant_id: "1",
  account: "",
  password: "",
  rememberMe: false,
  uuid: "",
})
import { ebaykdToken } from "@/api/system/index.js"
const getParams = (url) => {
  const regex = /[?&]([^=#]+)=([^&#]*)/g
  const params = {}
  let match
  while ((match = regex.exec(url))) {
    params[decodeURIComponent(match[1])] = decodeURIComponent(match[2])
  }
  return params
}
// const uuid = window.location.search.split("uuid=") ? window.location.search.split("uuid=")[1] : ""
const uuid = getParams(window.location.href)?.uuid || ""
// let code = window.location.search.split("code=")
let code = getParams(window.location.href)?.code || ""
//获取飞书二维码参数.
const getFeishu = async () => {
  await getFeishuApp().then((res) => {
    nextTick(() => {
      loading.value = true
       let redirect_uri = res.data.redirect_uri
      if (getParams(window.location.href)?.sys == "ebay_kd") {
        redirect_uri = redirect_uri + "?sys=ebay_kd"
      }
     
      const url = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${res.data.client_id}&redirect_uri=${redirect_uri}&response_type=code&state=STATE`
      const QRLoginObj = window.QRLogin({
        id: "login_container",
        goto: url,
        width: "300",
        height: "300",
        style: "width:258px;height:258px;margin:0 auto;border:1px solid #ebeaea;border-radius: 8px;background-color: #fff;", //可选的，二维码html标签的style属性
      })
      const handleMessage = function (event) {
        const origin = event.origin
        if (QRLoginObj.matchOrigin(origin)) {
          const loginTmpCode = event.data
          
          window.location.href = `${url}&tmp_code=${loginTmpCode}`
        }
      }
      if (typeof window.addEventListener != "undefined") {
        window.addEventListener("message", handleMessage, false)
      } else if (typeof window.attachEvent != "undefined") {
        window.attachEvent("onmessage", handleMessage)
      }
      loading.value = false
      if (code.length > 1) {
        loading.value = true
        userStore
          .qrLogim({ redirect_uri: res.data.redirect_uri, code: code })
          .then(async () => {
            if (getParams(window.location.href)?.sys == "ebay_kd") {
              try {
                const { data } = await ebaykdToken()
                window.location.href = `${data}&sys=ebay_kd`
              } catch (error) {
                router.push({ path: "/index" })
              }
            } else {
              router.push({ path: "/index" })
            }
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
  })
}
getFeishu()
const handleToggleType = () => {
  loginQr.value = !loginQr.value
  if (loginQr.value) {
    getFeishu()
  }
}

const loginRules = {
  account: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
}
const loading = ref(false)
// 验证码开关
// 注册开关
const register = ref(false)
const redirect = ref(undefined)
const handleLogin = () => {
  // 去除uuid验证
  // if (!uuid) { ElMessage.error('uuid为空，请联系管理员获取！'); return false }
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("account", loginForm.value.account, { expires: 30 })
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove("account")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      // 调用action的登录方法
      loginForm.value.uuid = uuid
      userStore
        .login(loginForm.value)
        .then(async () => {
          loading.value = false
          console.warn("------------------>>>执行硬刷新")
          if (getParams(window.location.href)?.sys == "ebay_kd") {
            const { data } = await ebaykdToken()
            // window.open(data, "_blank")
            window.location.href = data
          } else {
            window.location.reload(true)
          }
        })
        .catch(() => {
          loading.value = false
        })
    }
  })
}

function getCookie() {
  const account = Cookies.get("account")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    tenant_id: loginForm.value.tenant_id,
    account: account === undefined ? loginForm.value.account : account,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  }
}

getCookie()
const getYear = () => {
  let date = new Date()
  year.value = date.getFullYear()
}
const year = ref(2024)
getYear()
</script>

<style lang="scss">
.login {
  .el-input__inner:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px #fff inset;
  }
}

.login-company {
  .el-input__inner,
  .el-input .el-select__caret {
    color: var(--el-color-primary);
  }
}
</style>
<style lang="scss" scoped>
.hotZone {
  position: absolute;
  width: 70px;
  height: 70px;
  right: 0;
  top: 0;
  cursor: pointer;
  z-index: 9999;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("https://xc-sz-erp.oss-cn-shenzhen.aliyuncs.com/login/bg.png");
  background-size: 100% 100%;

  &-bg-img {
    position: absolute;
    left: -20%;
    bottom: -32%;
    min-width: 900px;
  }

  &-img {
    width: 50vw;
    height: 560px;
  }

  &-qr {
    font-size: 186px;
    line-height: 140px;
    text-align: center;

    svg {
      display: inline-block;
    }
  }
}

.login-right {
  display: none;
}

@media (min-width: 1380px) {
  .login-bg-img {
    left: 0px;
  }

  .login-right {
    width: 140px;
    display: block;
  }
}

@media (min-width: 2570px) {
  .login-bg-img {
    left: 12%;
  }

  .login-right {
    width: 200px;
  }
}

.title {
  font-size: 22px;
  margin: 10px 0 30px;
  text-align: center;
  color: #000;
  user-select: none;
}

.login-form {
  position: relative;
  z-index: 1;
  flex: 0 0 370px;
  border-radius: 6px;
  background: #ffffff;
  width: 370px;
  height: 500px;
  box-shadow: -5px 5px 25px 0 rgba($color: #3487ff, $alpha: 0.2);
  overflow: hidden;

  &-box {
    height: 512px;
    position: relative;
    padding: 25px 25px 5px 25px;
    background-color: transparent;
    background-image: url("https://xc-sz-erp.oss-cn-shenzhen.aliyuncs.com/login/login_bg.png");
    background-size: auto;
    background-repeat: no-repeat;
    background-position: center center;
    overflow: hidden;
    box-sizing: border-box;
  }

  &-popover {
    // display: none;
    position: absolute;
    right: 18px;
    top: 22px;
    user-select: none;

    small {
      position: absolute;
      left: 2px;
      top: 17px;
      transform: rotate(45deg) scale(0.9);
      font-size: 12px;
      white-space: nowrap;
      color: var(--el-color-primary);
      user-select: none;
    }
  }

  &-toggle {
    position: absolute;
    top: -54px;
    right: -54px;
    width: 100px;
    height: 100px;
    text-align: center;
    z-index: 2;
    background-color: #e2e9f7;
    transform: rotate(-135deg);
    cursor: pointer;
    box-shadow: -2px -2px 5px 1px rgba($color: var(--el-color-primary), $alpha: 0.2);

    &:hover + .login-form-popover {
      display: block;
    }

    svg {
      display: inline-block;
      margin-top: -4.5px;
      color: var(--el-color-primary);
      font-size: 34px;
      transform: rotate(-225deg);
    }
  }

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 28px;
  line-height: 28px;
  position: fixed;
  z-index: 2;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.2);
  line-height: 20px;
}

.login-form-phone {
  text-align: center;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #cdcfd4;
  line-height: 17px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
